﻿using ProjectCloth.Entity;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class ReceivableAccountFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        List<Product> productList = new List<Product>();// 
        private bool IsNew = true;
        private int ReceivableAccountId = 0;
        private ReceivableAccount receivableAccount;
        public ReceivableAccountFrm(int id)
        {
            IsNew = false;
            ReceivableAccountId = id;
            receivableAccount = db.ReceivableAccounts.Find(id);
            InitializeComponent();
            inmoneycbb.DataSource = db.CashAccounts.ToList();
            inmoneycbb.ValueMember = "Id";
            inmoneycbb.DisplayMember = "TradeTypeName";
            inmoneycbb.SelectedValue = 0;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.ValueMember = "Id";
            makerCbx.DisplayMember = "Name";
            productList = db.Products.ToList();
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("码");
            GenderColumn.Items.Add("米");
            GenderColumn.DefaultCellStyle.NullValue = "码";

            //初始化单据
            companyTxt.Text = receivableAccount.PayCompany;
            //makerCbx.Text = "";
            makerCbx.SelectedValue = receivableAccount.MakerId;
            inmoneyTime.Value = receivableAccount.MakerTime.Value;
            RelatedNoTxt.Text = receivableAccount.RelatedNo;
            summaryTxt.Text = receivableAccount.Summary;
            RemarkTxt.Text = receivableAccount.Remark;
            inmoneyAmountTxt.Text = receivableAccount.Amount.ToString();
            var list = (from re in db.ReceivableAccountItems.Where(o => o.ReceivableAccountId == id)
                        join pro in db.Products on re.ProductId equals pro.Id
                        select new
                        {
                            ProductNo = pro.ProductNo,
                            OrderItemId = re.Id,
                            re.ColorType,
                            re.Quantity,
                            re.Price,
                            Sum = re.Amount,
                            re.Remark,
                            //re.Amount,
                            //re.CreateDate,
                            //re.CreatorId,
                            //re.CreatorName,
                            //re.CustormerName,                          
                            //re.MakerId,
                            //re.MakerName,
                            //re.OrderItemStatus,                       
                            //re.ProductId,                        
                            //re.ReceivableAccountId,                    
                            //Unit=(Entity.Enum.Unit)re.Unit,

                        }).ToList();
            dataGridView1.DataSource = list;
        }
        public ReceivableAccountFrm()
        {
            InitializeComponent();
            inmoneycbb.DataSource = db.CashAccounts.ToList();
            inmoneycbb.ValueMember = "Id";
            inmoneycbb.DisplayMember = "TradeTypeName";
            inmoneycbb.SelectedValue = 0;
            makerCbx.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            makerCbx.ValueMember = "Id";
            makerCbx.DisplayMember = "Name";
            productList = db.Products.ToList();
            DataGridViewComboBoxColumn GenderColumn = Unit as DataGridViewComboBoxColumn;
            GenderColumn.Items.Add("码");
            GenderColumn.Items.Add("米");
            GenderColumn.DefaultCellStyle.NullValue = "码";
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                using (TransactionScope tran = new TransactionScope())
                {
                    var dgv = dataGridView1;
                    var account = db.CashAccounts.Find((int)inmoneycbb.SelectedValue);
                    if (string.IsNullOrEmpty(inmoneyAmountTxt.Text) || Convert.ToDecimal(inmoneyAmountTxt.Text) <= 0)
                    {
                        MessageBox.Show("请输入正确金额！");
                        return;
                    }
                    if (inmoneycbb.SelectedValue == null || (int)inmoneycbb.SelectedValue <= 0)
                    {
                        MessageBox.Show("请选择收款账户！");
                        return;
                    }
                    if (IsNew)
                    {
                        var receivalbe = new ReceivableAccount()
                        {
                            CreateTime = DateTime.Now,
                            IsReceived = true,
                            PayCompany = companyTxt.Text,
                            //CreatorId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                            MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                            MakerName = makerCbx.Text != null ? makerCbx.Text : "",
                            Summary = summaryTxt.Text,
                            Remark = RemarkTxt.Text,
                            RelatedNo = RelatedNoTxt.Text,
                            MakerTime = inmoneyTime.Value,
                            ReceivedAccountId = inmoneycbb.SelectedValue != null ? (int)inmoneycbb.SelectedValue : 0,
                            Amount = inmoneyAmountTxt.Text != null ? Convert.ToDecimal(inmoneyAmountTxt.Text) : 0,
                            ReceivedAccountName = !string.IsNullOrEmpty(inmoneycbb.Text) ? inmoneycbb.Text : ""

                        };
                        db.ReceivableAccounts.Add(receivalbe);
                        var result = db.SaveChanges();
                        if (result > 0)
                        {
                            #region 列表
                            List<ReceivableAccountItem> items = new List<ReceivableAccountItem>();
                            for (int i = 0; i < dgv.RowCount - 1; i++)
                            {
                                if (dgv.Rows[i].Cells["ProductNo"] != null && dgv.Rows[i].Cells["ProductNo"].Value != null)
                                {
                                    //var dropDown = dgv.CurrentRow.Cells["ProductNo"];
                                    //var productno = dropDown.EditedFormattedValue.ToString();
                                    var productno = dgv.Rows[i].Cells["ProductNo"].Value.ToString();
                                    var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();
                                    if (product == null)
                                    {
                                        MessageBox.Show("未选择商品！");
                                        return;
                                    }
                                    if (product != null)//&& sel)
                                    {
                                        ReceivableAccountItem sd = new ReceivableAccountItem()
                                        {
                                            ReceivableAccountId = receivalbe.Id,
                                            //OrderId = order.Id,
                                            ProductId = product.Id,//商品
                                            Quantity = Convert.ToDecimal(dgv.Rows[i].Cells["Quantity"].Value),//数量                                                                                       //Remark = dataGridView1.Rows[i].Cells[7].Value.ToString(),//备注
                                            Amount = Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value),//估算总金额
                                            ColorType = dgv.Rows[i].Cells["ColorType"].Value == null ? "" : dgv.Rows[i].Cells["ColorType"].Value.ToString(),
                                            Unit = (int)(Enum.Parse(typeof(Entity.Enum.Unit), dgv.Rows[i].Cells["Unit"].EditedFormattedValue != null ? dgv.Rows[i].Cells["Unit"].EditedFormattedValue.ToString().Trim() : "码")),//单位
                                            Price = Convert.ToDecimal(dgv.Rows[i].Cells["Price"].Value),//价格
                                            Remark = dgv.Rows[i].Cells["remark"].Value == null ? "" : dgv.Rows[i].Cells["remark"].Value.ToString(),
                                            CreateDate = DateTime.Now,
                                            CreatorId = LoginInfo.GetLoginInfo().UserId,
                                            CreatorName = LoginInfo.GetLoginInfo().UserName,
                                            //OrderNo = order.OrderNo,
                                            MakerId = Convert.ToInt32(makerCbx.SelectedValue)
                                        };
                                        items.Add(sd);
                                    }
                                }

                            }
                            if (items.Count() > 0)
                            {
                                db.ReceivableAccountItems.AddRange(items);
                                receivableAccount = receivalbe;
                            }
                            else
                            {
                                MessageBox.Show("保存失败！");
                                return;
                            }
                            #endregion
                        }
                    }

                    else if (receivableAccount.IsReceived == false)
                    {
                        receivableAccount.IsReceived = true;
                    }
                    else
                    {
                        MessageBox.Show("已为收款完成状态！");
                        return;
                    }
                    var oldAmount = account.Amount;
                    account.OriginalAmount = oldAmount;
                    account.Amount += receivableAccount.Amount;
                    account.UpdateTime = DateTime.Now;
                    var log = new CashAccountLog()
                    {
                        CashAccountId = account.Id,
                        CreateTime = DateTime.Now,
                        CurrentAmount = account.Amount,
                        OriginalAmount = oldAmount,
                        Remark = RemarkTxt.Text,
                        MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                        MakerTime = inmoneyTime.Value,
                        RelatedObject = companyTxt.Text,
                        Source = "收款单",
                        VariableAmount = receivableAccount.Amount,
                        LoginId = LoginInfo.GetLoginInfo().UserId,
                    };
                    db.CashAccountLogs.Add(log);
                    db.SaveChanges();
                    tran.Complete();
                    MessageBox.Show("保存成功！");
                    if (!IsNew)
                    {
                        var mainFrm = MainFrm.CreateInstrance();
                        var tab = mainFrm.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                        var tabControl = tab;
                        if (tab != null)
                        {
                            tabControl = tab as TabControl;
                            foreach (TabPage tabp in tabControl.TabPages)
                            {
                                if (tabp.Name == "ReceivableAccountFrm")
                                {
                                    tabControl.TabPages.Remove(tabp);
                                }
                            }
                        }
                    }
                    else
                    {
                        dataGridView1.Rows.Clear();
                        companyTxt.Text = "";
                        inmoneyAmountTxt.Text = "0";
                        RelatedNoTxt.Text = "";
                        summaryTxt.Text = "";
                        RemarkTxt.Text = "";
                    }      
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("非法输入！" + error.ToString());
            }

        }
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                var form = new ProductSelectFrm();
                var result = form.ShowDialog();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.productNo;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentRow.Cells["ColorType"].Selected == true && dataGridView1.CurrentRow.Cells["ColorType"].Value != null)
            {
                string txt = dataGridView1.CurrentRow.Cells["ColorType"].Value.ToString();
                dataGridView1.CurrentRow.Cells["ColorType"].Value = txt + "#";
            }
        }
        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            var dgv = dataGridView1;
            //TextBox salesum = (TextBox)this.Controls.Find("inmoneyAmountTxt", true)[0];
            bool _disable = false;

            switch (keyData)
            {
                case Keys.Enter:
                    if (dgv.CurrentRow != null)
                    {
                        if (dgv.CurrentRow.Cells["ProductNo"] != null && dgv.CurrentRow.Cells["ProductNo"].Value != null)
                        {

                            var productno = dgv.CurrentRow.Cells["ProductNo"].Value.ToString();
                            var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();// productlist.Where(p => p.ProductId == productno).FirstOrDefault();
                            if (product != null)//&& sel)
                            {
                                if (dgv.CurrentRow.Cells["ProductName"].Value == null && dgv.CurrentRow.Cells["Price"].Value == null)
                                {
                                    //SendKeys.Send("{Tab}");
                                    //dgv.CurrentRow.Cells["ProductNo"].Value = product.ProductNo;
                                    //dgv.CurrentRow.Cells["ProductName"].Value = product.Name;
                                    //dgv.CurrentRow.Cells["ColorType"].Value = product.ColorType;
                                    dgv.CurrentRow.Cells["Price"].Value = dgv.CurrentRow.Cells["Unit"].Value == null || dgv.CurrentRow.Cells["Unit"].Value.ToString() == "码" ? product.BatchPrice : product.Price;
                                    //Unit.DefaultCellStyle.NullValue = _size == 0 ? "米" : "码";

                                }
                                dgv.CurrentRow.Cells["Sum"].Value =
                                         Convert.ToDecimal(dgv.CurrentRow.Cells["Price"].Value) * Convert.ToDecimal(dgv.CurrentRow.Cells["Quantity"].Value);//计算金额
                            }
                            if (dgv.CurrentRow.Cells["ColorType"].Selected == true)
                            {
                                SendKeys.Send("{Tab}");
                                //SendKeys.Send("{Tab}"); 
                            }
                            if (dgv.CurrentRow.Cells["Quantity"].Selected == true)
                            {
                                SendKeys.Send("{Tab}");
                            }
                            if (dgv.CurrentRow.Cells["Sum"].Selected == true)
                            {
                                decimal paysum = 0;
                                decimal quantity = 0;
                                for (int i = 0; i < dgv.RowCount - 1; i++)
                                {
                                    paysum += Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value);
                                    quantity += Convert.ToDecimal(dgv.Rows[i].Cells["Quantity"].Value);
                                }
                                //littlecountTxt.Text = quantity.ToString();
                                //salesum.Text = paysum.ToString();
                            }
                        }
                        SendKeys.Send("{Tab}");
                    }
                    else
                    {
                        if (summaryTxt.Focused == true)
                        {
                            dgv.Focus();
                        }
                    }

                    _disable = true;
                    break;
                case Keys.F12:
                    {
                        SaveBtn_Click(null, null);
                        _disable = true;
                        break;
                    }
                default:
                    break;
            }

            return _disable;
        }
        #endregion
        /// <summary>
        /// 未收保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveUnreceiveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsNew == false) return;
                using (TransactionScope tran = new TransactionScope())
                {


                    var dgv = dataGridView1;
                    var account = db.CashAccounts.Find((int)inmoneycbb.SelectedValue);
                    if (string.IsNullOrEmpty(inmoneyAmountTxt.Text) || Convert.ToDecimal(inmoneyAmountTxt.Text) <= 0)
                    {
                        MessageBox.Show("请输入正确金额！");
                        return;
                    }
                    if (inmoneycbb.SelectedValue == null || (int)inmoneycbb.SelectedValue <= 0)
                    {
                        MessageBox.Show("请选择收款账户！");
                        return;
                    }
                    var receivalbe = new ReceivableAccount()
                    {
                        CreateTime = DateTime.Now,
                        IsReceived = false,
                        PayCompany = companyTxt.Text,
                        //CreatorId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                        MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                        MakerName = makerCbx.Text != null ? makerCbx.Text : "",
                        Summary = summaryTxt.Text,
                        Remark = RemarkTxt.Text,
                        RelatedNo = RelatedNoTxt.Text,
                        MakerTime = inmoneyTime.Value,
                        ReceivedAccountId = inmoneycbb.SelectedValue != null ? (int)inmoneycbb.SelectedValue : 0,
                        Amount = inmoneyAmountTxt.Text != null ? Convert.ToDecimal(inmoneyAmountTxt.Text) : 0,
                        ReceivedAccountName = !string.IsNullOrEmpty(inmoneycbb.Text) ? inmoneycbb.Text : ""

                    };
                    db.ReceivableAccounts.Add(receivalbe);
                    var result = db.SaveChanges();
                    if (result > 0)
                    {
                        #region 列表
                        List<ReceivableAccountItem> items = new List<ReceivableAccountItem>();
                        for (int i = 0; i < dgv.RowCount - 1; i++)
                        {
                            if (dgv.Rows[i].Cells["ProductNo"] != null && dgv.Rows[i].Cells["ProductNo"].Value != null)
                            {
                                //var dropDown = dgv.CurrentRow.Cells["ProductNo"];
                                //var productno = dropDown.EditedFormattedValue.ToString();
                                var productno = dgv.Rows[i].Cells["ProductNo"].Value.ToString();
                                var product = productList.Where(p => p.ProductNo.Contains(productno)).FirstOrDefault();
                                if (product == null)
                                {
                                    MessageBox.Show("未选择商品！");
                                    return;
                                }
                                if (product != null)//&& sel)
                                {
                                    ReceivableAccountItem sd = new ReceivableAccountItem()
                                    {
                                        ReceivableAccountId = receivalbe.Id,
                                        //OrderId = order.Id,
                                        ProductId = product.Id,//商品
                                        Quantity = Convert.ToDecimal(dgv.Rows[i].Cells["Quantity"].Value),//数量                                                                                       //Remark = dataGridView1.Rows[i].Cells[7].Value.ToString(),//备注
                                        Amount = Convert.ToDecimal(dgv.Rows[i].Cells["Sum"].Value),//估算总金额
                                        ColorType = dgv.Rows[i].Cells["ColorType"].Value == null ? "" : dgv.Rows[i].Cells["ColorType"].Value.ToString(),
                                        Unit = (int)(Enum.Parse(typeof(Entity.Enum.Unit), dgv.Rows[i].Cells["Unit"].EditedFormattedValue != null ? dgv.Rows[i].Cells["Unit"].EditedFormattedValue.ToString().Trim() : "码")),//单位
                                        Price = Convert.ToDecimal(dgv.Rows[i].Cells["Price"].Value),//价格
                                        Remark = dgv.Rows[i].Cells["remark"].Value == null ? "" : dgv.Rows[i].Cells["remark"].Value.ToString(),
                                        CreateDate = DateTime.Now,
                                        CreatorId = LoginInfo.GetLoginInfo().UserId,
                                        CreatorName = LoginInfo.GetLoginInfo().UserName,
                                        //OrderNo = order.OrderNo,
                                        MakerId = Convert.ToInt32(makerCbx.SelectedValue)
                                    };
                                    items.Add(sd);
                                }
                            }

                        }
                        if (items.Count() > 0)
                            db.ReceivableAccountItems.AddRange(items);
                        #endregion
                        //var oldAmount = account.Amount;
                        //account.OriginalAmount = oldAmount;
                        //account.Amount += receivalbe.Amount;
                        //account.UpdateTime = DateTime.Now;
                        //var log = new CashAccountLog()
                        //{
                        //    CashAccountId = account.Id,
                        //    CreateTime = DateTime.Now,
                        //    CurrentAmount = account.Amount,
                        //    OriginalAmount = oldAmount,
                        //    Remark = RemarkTxt.Text,
                        //    MakerId = makerCbx.SelectedValue != null ? (int)makerCbx.SelectedValue : 0,
                        //    MakerTime = inmoneyTime.Value,
                        //    RelatedObject = companyTxt.Text,
                        //    Source = "收款单",
                        //    VariableAmount = receivalbe.Amount,
                        //    LoginId = LoginInfo.GetLoginInfo().UserId,
                        //};
                        //db.CashAccountLogs.Add(log);
                        db.SaveChanges();
                        tran.Complete();
                        MessageBox.Show("保存成功！");
                        dataGridView1.Rows.Clear();
                        companyTxt.Text = "";
                        inmoneyAmountTxt.Text = "0";
                        RelatedNoTxt.Text = "";
                        summaryTxt.Text = "";
                        RemarkTxt.Text = "";
                    }
                    else MessageBox.Show("保存失败！");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("非法输入！" + error.ToString());
            }
        }
    }
}
